package cn.cjlmonster.hyouka_assistant

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.util.Log
import cn.cjlmonster.hyouka_assistant.ai.AIAssistantActivity
import cn.cjlmonster.hyouka_assistant.ai.WebBrowser
import cn.cjlmonster.hyouka_assistant.ai.startUI
import cn.cjlmonster.hyouka_assistant.base.BaseActivity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler


/**
 * WKPlugin
 *
 * @author cjl
 * @date 2025/6/22 15:42
 */
@SuppressLint("StaticFieldLeak")
object WKPlugin : MethodCallHandler {
    const val TAG = "语音识别测试"

    private const val CHANNEL_NAME = "cn.cjlmonster.hyouka/assistant"

    private var methodChannel: MethodChannel? = null
    private var activity: Activity? = null

    val context: Context?
        get() = activity

    private val activityMap = mutableMapOf<Int, BaseActivity<*>>()

    fun addActivity(activity: BaseActivity<*>) {
        activityMap[activity.hashCode()] = activity
    }

    fun removeActivity(activity: BaseActivity<*>) {
        activityMap.remove(activity.hashCode())
    }

    private fun removeAllActivity() {
        val activityList = activityMap.values.toMutableList()
        Log.i(TAG, "removeAllActivity: ${activityList.size}")
        activityList.forEach {
            if (!it.isFinishing) {
                it.finish()
            }
        }
        activityList.clear()
        activityMap.clear()
    }

    fun bindMethodChannel(flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        methodChannel = MethodChannel(flutterPluginBinding.binaryMessenger, CHANNEL_NAME).also {
            it.setMethodCallHandler(this)
        }
    }

    fun unbindMethodChannel() {
        methodChannel?.setMethodCallHandler(null)
        methodChannel = null
    }

    fun bindActivity(activity: Activity) {
        WKPlugin.activity = activity
    }

    fun unbindActivity() {
        activity = null
    }

    fun callMethod(key: Int, id: Int, method: String, callback: String, extras: Map<*, *>? = null) {
        methodChannel?.invokeMethod(
            method, mapOf(
                "key" to key,
                "id" to id,
                "method" to method,
                "callback" to callback,
                "extras" to extras
            )
        )
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        Log.i(TAG, "onMethodCall: ${call.method}, args: ${call.arguments}")
        val args = (call.arguments as? Map<*, *>) ?: emptyMap<Any?, Any?>()
        when (call.method) {
            "openAssistantSheet" -> {
                activity?.startUI(AIAssistantActivity::class.java) {
                    putExtra("url", args["url"] as String)
                    putExtra("marginTop", args["marginTop"] as Int)
                }
                result.success(true)
            }

            "openUrl" -> {
                activity?.run {
                    val url = args["url"] as String
                    val query = args["query"] as? Map<*, *>
                    WebBrowser.to(this, url, query)
                }
            }

            "removeAllActivity" -> {
                removeAllActivity()
            }

            "flutterCallback" -> {
                val key = args["key"] as Int
                val id = args["id"] as Int
                val method = args["method"] as String
                val callback = args["callback"] as String
                val data = args["data"] as Map<*, *>
                activityMap[key]?.onFlutterCallback(id, method, callback, data)
            }

            "recognizeReceived" -> {
                val key = args["key"] as Int
                val data = args["data"] as Map<*, *>
                activityMap[key]?.onRecognizeReceived(data)
            }

            else -> result.notImplemented()
        }
    }
}